Component({
  properties: {
    // 接收外部传入的上传函数
    uploadHandler: {
      type: Function,
      value: () => {}
    },
    // 其他属性保持不变
    maxCount: {
      type: Number,
      value:3 
    },
    images: {
      type: Array,
      value: []
    },
    sizeType: {
      type: Array,
      value: ['original', 'compressed']
    },
    sourceType: {
      type: Array,
      value: ['album', 'camera']
    }
  },
  data: {
    currentImages: [] as string[]
  },
  observers: {
    'images': function(images) {
      this.setData({
        currentImages: [...images] 
      });
    }
  },
  methods: {
    // 选择图片
    chooseImage() {
      const { maxCount, currentImages, sizeType, sourceType } = this.data;
      const count = maxCount - currentImages.length;
      
      if (count <= 0) {
        wx.showToast({
          title: `最多只能上传${maxCount}张图片`,
          icon: 'none'
        });
        return;
      }
      
      wx.chooseImage({
        count,
        sizeType,
        sourceType,
        success: (res) => {
          if (this.properties.uploadHandler) {
            this.handleExternalUpload(res.tempFilePaths);
          } else {
            this.handleInternalUpload(res.tempFilePaths);
          }
        },
        fail: (err) => {
          console.error('选择图片失败:', err);
        }
      });
    },
    
    // 处理内部上传
    handleInternalUpload(tempFilePaths) {
      const promises = tempFilePaths.map((tempFilePath) => {
        return this.uploadImage(tempFilePath);
      });
      
      Promise.all(promises)
        .then((results) => {
          const newImages = this.data.currentImages.concat(results);
          this.setData({ currentImages: newImages });
          this.triggerEvent('change', { images: newImages });
        })
        .catch((err) => {
          console.error('上传图片失败:', err);
          wx.showToast({
            title: '上传图片失败',
            icon: 'none'
          });
        });
    },
    
    // 处理外部上传
    handleExternalUpload(tempFilePaths) {
      const { uploadHandler } = this.properties;
      
      uploadHandler(tempFilePaths)
        .then((results) => {
          const newImages = this.data.currentImages.concat(results);
          this.setData({ currentImages: newImages });
          this.triggerEvent('change', { images: newImages });
        })
        .catch((err) => {
          console.error('外部上传失败:', err);
          wx.showToast({
            title: err.message || '上传失败',
            icon: 'none'
          });
        });
    },
    
    // 内部上传方法（当外部没有提供上传函数时使用）
    uploadImage(tempFilePath) {
      return new Promise((resolve, reject) => {
        if (!this.properties.uploadUrl) {
          // 如果没有提供上传URL，则直接返回临时路径
          resolve({
            url: tempFilePath,
            isTemp: true
          });
          return;
        }
        
        wx.uploadFile({
          url: this.properties.uploadUrl,
          filePath: tempFilePath,
          name: 'file',
          success: (res) => {
            if (res.statusCode === 200) {
              try {
                const data = JSON.parse(res.data);
                resolve(data);
              } catch (e) {
                resolve({
                  url: tempFilePath,
                  isTemp: true,
                  error: '无法解析服务器响应'
                });
              }
            } else {
              reject(new Error(`上传失败，状态码: ${res.statusCode}`));
            }
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    },
    
    // 删除图片
    deleteImage(e) {
      const index = e.currentTarget.dataset.index;
      const newImages = [...this.data.currentImages];
      newImages.splice(index, 1);
      
      this.setData({ currentImages: newImages });
      this.triggerEvent('change', { images: newImages });
    },
    
    // 预览图片
    previewImage(e) {
      const index = e.currentTarget.dataset.index;
      const urls = this.data.currentImages.map(img => img.url || img);
      
      wx.previewImage({
        current: urls[index],
        urls
      });
    }
  }
});
    